package edu.whu.powersoap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.baidu.mapapi.cloud.CloudListener;
import com.baidu.mapapi.cloud.CloudManager;
import com.baidu.mapapi.cloud.CloudPoiInfo;
import com.baidu.mapapi.cloud.CloudSearchResult;
import com.baidu.mapapi.cloud.DetailSearchResult;
import com.baidu.mapapi.cloud.LocalSearchInfo;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import edu.whu.powersoap.R;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TimeZone;

public class JobCreateActivity extends Activity implements CloudListener {

	private static final String TAG = "JobCreateActivity";
	private ListView mListView;
	private EditText mEditText;
	private MapView mMapView;
	private BaiduMap mBaiduMap;
	private ArrayList<CloudPoiInfo> mPoiList = new ArrayList<CloudPoiInfo>();
	private Context mContext;
	private String chosed_name;
	private String chose_name;
	public String username = MainActivity.user;
	public int bflag = 0;
	private int clickFlag = 0;
//	private View view;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mContext = JobCreateActivity.this;

//		mInflater = LayoutInflater.from(this);
		
		CloudManager.getInstance().init(JobCreateActivity.this);

		LocalSearchInfo info = new LocalSearchInfo();
		info.ak = "A4916bd1a0ce990660677a7d773b7153";
		info.geoTableId = 69300;
		info.tags = "";
		info.q = "";
		info.region = "武汉市";
		info.pageSize = 50;
		CloudManager.getInstance().localSearch(info);

		setContentView(R.layout.job_create);

		mMapView = (MapView) findViewById(R.id.mapView);
		mListView = (ListView) findViewById(R.id.listView);
		mListView.setVisibility(View.GONE);
		
		
		TextView text = (TextView) findViewById(R.id.texttext);
		text.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				if((clickFlag % 2) == 0){
					mListView.setVisibility(View.VISIBLE);
					clickFlag = clickFlag % 2 + 1;
				}else{
					mListView.setVisibility(View.GONE);
					clickFlag --;
				}
			}
			
		});
		
//		view = mInflater.inflate(
//				R.layout.simple_list_item_2_single_choice, null);
//		view = mInflater.inflate(
//				R.layout.simple_list_item_2_single_choice, mListView,
//				false);
//		button = (CheckBox) view.findViewById(R.id.checkBox);
//		
//		button2 = (CheckBox) findViewById(R.id.checkBox2);
//		button2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
//
//			@Override
//			public void onCheckedChanged(CompoundButton btn,
//					boolean isChecked) {
//				
//				if (isChecked) {
//					button.setChecked(true);
//					
//				} else {
//					button.setChecked(false);
//				}
//
//			}
//
//		});
		
		mBaiduMap = mMapView.getMap();

		mEditText = (EditText) findViewById(R.id.editText1);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		mEditText.setText(sdf.format(new Date()));
				
		//分配执行人
		Button btn1 = (Button) findViewById(R.id.button1);
		if(btn1 != null){
			btn1.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View arg0){
					Cursor cursor = JobCreateActivity.this.getContentResolver().query(UserProvider.CONTENT_URI, new String[]
							{
								UserProvider.VOL_ID + " as _id",
								UserProvider.VOL_NAME,
								UserProvider.VOL_PASSWORD,
								UserProvider.VOL_FLAG
							}, null, null, null);
					int j = 0;
					for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
						j++;
					}
					int i = 0;
					final boolean check[] = new boolean[j];
					final String[] name = new String[j];
					final ArrayList<String> chose = new ArrayList<String>();
					final HashMap<Boolean , String> hashmap = new HashMap<Boolean , String>();
					
					for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
						int id = cursor.getColumnIndex(UserProvider.VOL_NAME);
						String name0 = cursor.getString(id);
						name[i] = name0;
						check[i] = false;
						hashmap.put(check[i], name[i]);
						i++;
					}
					
						Dialog dialog = new AlertDialog.Builder(JobCreateActivity.this)
						.setTitle("选择用户")
						.setIcon(R.drawable.alert_dialog_icon)
						.setMultiChoiceItems(
								name, 
								check,
								new DialogInterface.OnMultiChoiceClickListener() 
								{
									public void onClick(DialogInterface dialog,
											int whichButton,
											boolean isChecked)
									{
										if(isChecked){
											check[whichButton] = true;
											hashmap.put(check[whichButton], name[whichButton]);
											chose_name = hashmap.get(true);
											chose.add(chose_name);
										}else{
											check[whichButton] = false;
										}
										
										
									}
								})
					.setPositiveButton("chose", new DialogInterface.OnClickListener(){
						public void onClick(DialogInterface dialog, int whichButton){
							 chosed_name = hashmap.get(true);
							 bflag = 1;
						}
					})
					.setNegativeButton("cancel", new DialogInterface.OnClickListener(){
						public void onClick(DialogInterface dialog, int whichButton){
							dialog.dismiss();
						}
					}).create();
					
					dialog.show();
				
				}
				});
			
			}
		
		//创建工单
		Button btnc = (Button) findViewById(R.id.job_create);
		btnc.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {			
					if(bflag==1 && mPoiList.size()>0){						
						ContentResolver cr = mContext.getContentResolver();
						Time time = new Time();
						time.setToNow();
						String c_time = time.year + "." + (time.month+1) + "." + time.monthDay +" "+
						time.hour + ":"+ time.minute + ":"+ time.second;
						/* insert new */
						ContentValues values = new ContentValues();
						
						values.put(JobProvider.VOLUMN_NUMBER, mEditText.getText()
								.toString());
						values.put(JobProvider.VOLUMN_STATUS, "created");
						values.put(JobProvider.VOLUMN_CREATE_TIME,
								c_time);
						values.put(JobProvider.VOLUMN_EXECUTOR, chosed_name);
						
						//此处在添加poilist时只是加入了一个点，有待完善	
						//4——5完善之后加入多个点，点之间用分号隔开
						String poiList = mPoiList.get(0).latitude + "," + mPoiList.get(0).longitude;						
						for (int i = 1 ; i<mPoiList.size(); i++){
							CloudPoiInfo info = mPoiList.get(i);
							String poi = info.latitude + ","+ info.longitude;
							poiList = poiList + ";" +poi;							
						}						
						values.put(JobProvider.VOLUMN_POI_LIST, poiList);
						Uri uri = cr.insert(JobProvider.CONTENT_URI, values);

						Log.i(TAG, "cr.insert uri=" + uri);

						Dialog dialog = new AlertDialog.Builder(JobCreateActivity.this)
								.setMessage("工单创建成功")
								.setTitle("提示")
								.setPositiveButton("确认",
										new DialogInterface.OnClickListener() {

											@Override
											public void onClick(DialogInterface dialog,
													int which) {
												dialog.dismiss();
												JobCreateActivity.this.finish();
											}
										}).create();

						dialog.show();						
					}else{
						if(bflag==0){
							final Dialog dialog1 = new AlertDialog.Builder(JobCreateActivity.this)
							.setMessage("请指定执行人")
							.setTitle("提示")
							.setPositiveButton("确认",
							new DialogInterface.OnClickListener() {		
							@Override
							public void onClick(DialogInterface dialog1, int which) 
							{
								dialog1.dismiss();
							}
							}).create();
								
							dialog1.show();											
						}else{
							final Dialog dialog1 = new AlertDialog.Builder(JobCreateActivity.this)
							.setMessage("请选择工作点")
							.setTitle("提示")
							.setPositiveButton("确认",
							new DialogInterface.OnClickListener() {		
							@Override
							public void onClick(DialogInterface dialog1, int which) 
							{
								dialog1.dismiss();
							}
							}).create();
								
							dialog1.show();																					
						}
					}

				}
		});

	}	
	
	
	private class PoiListAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private CheckBox button2;
		private CheckBox button;
		private List<CloudPoiInfo> mList;		
		public PoiListAdapter(Context context, List<CloudPoiInfo> mList) {
			super();
			this.mList = mList;
			Log.d(TAG, "PoiListAdapter count=" + getCount());
			mInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			return mList.size();
		}

		@Override
		public Object getItem(int position) {
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent ) {
			final View v;
			if (convertView == null) {
				v = mInflater.inflate(
						R.layout.simple_list_item_2_single_choice, parent,
						false);
//				v = view;
			} else {
				v = convertView;
			}
			
			final CloudPoiInfo info = (CloudPoiInfo) getItem(position);
			TextView text1 = (TextView) v.findViewById(android.R.id.text1);
			TextView text2 = (TextView) v.findViewById(android.R.id.text2);
			text1.setText(info.title);
			text2.setText(info.address);			
			
			button = (CheckBox) v.findViewById(R.id.checkBox);
			button.setTag(info);
	
			button2 = (CheckBox) findViewById(R.id.checkBox2);
			button2.setOnCheckedChangeListener(new OnCheckedChangeListener() {								
				@Override
				public void onCheckedChanged(CompoundButton btn,
						boolean isChecked) {
//					CheckBox button1 = (CheckBox) v.findViewById(R.id.checkBox);
					if (isChecked) {
						button.setChecked(true);
						Log.d(TAG, "aaaaaaaaaaabbbbbbbbbbcccccccc");
					} else {
						button.setChecked(false);
					}

				}

			});
			button.setOnCheckedChangeListener(new OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(CompoundButton btn,
						boolean isChecked) {
					CloudPoiInfo info = (CloudPoiInfo) btn.getTag();
					if (isChecked) {
						mPoiList.add(info);
					} else {
						mPoiList.remove(info);
					}

					mBaiduMap.clear();
					BitmapDescriptor bd = BitmapDescriptorFactory
							.fromResource(R.drawable.icon_gcoding);
					LatLng ll;
					LatLngBounds.Builder builder = new LatLngBounds.Builder();
					for (CloudPoiInfo i : mPoiList) {
						ll = new LatLng(i.latitude, i.longitude);
						OverlayOptions oo = new MarkerOptions().icon(bd)
								.position(ll);
						mBaiduMap.addOverlay(oo);
						builder.include(ll);
					}
					LatLngBounds bounds = builder.build();
					MapStatusUpdate u = MapStatusUpdateFactory
							.newLatLngBounds(bounds);
					mBaiduMap.animateMapStatus(u);
				}

			});
			
			v.setTag(info);

			return v;
		}
	}

	@Override
	public void onGetDetailSearchResult(DetailSearchResult result, int error) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onGetSearchResult(CloudSearchResult result, int error) {
		mListView.setAdapter(new PoiListAdapter(this, result.poiList));

	}

}
